﻿namespace BM.Tools.WebControls.MForm.BlogExample
{    
    using System.Collections.ObjectModel;
    using System.Web;    
    using System.Xml;
    using System.Xml.Serialization;

    /// <summary>
    /// This class is used for multiple <see cref="BlogEntry"/> objects persistance.
    /// The entries are persisted in an xml file using xml serialization. 
    /// This is just for making the example easy and concise.
    /// </summary>
    public class BlogEntries : Collection<BlogEntry>
    {
        /// <summary>
        /// Gets the <see cref="BlogEntries"/> object from the persistence medium.
        /// </summary>
        /// <returns>
        /// The <see cref="BlogEntries"/> object,
        /// </returns>
        public static BlogEntries Get()
        {
            if (HttpContext.Current.Session["blogEntries"] == null)
            {
                try
                {
                    HttpContext.Current.Session["blogEntries"] = Load(HttpContext.Current.Request.MapPath("entries.xml"));
                }
                catch
                {
                    HttpContext.Current.Session["blogEntries"] = new BlogEntries();
                }
            }

            return HttpContext.Current.Session["blogEntries"] as BlogEntries;
        }

        /// <summary>
        /// Loads the <see cref="BlogEntries"/> object from a file
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        /// <returns>
        /// The persisted blog entries
        /// </returns>
        public static BlogEntries Load(string filePath)
        {
            var serializer = new XmlSerializer(typeof(BlogEntries));
            using (var reader = XmlReader.Create(filePath))
            {
                return serializer.Deserialize(reader) as BlogEntries;
            }
        }

        /// <summary>
        /// Saves the <see cref="BlogEntries"/> object to a file
        /// </summary>
        /// <param name="filePath">
        /// The file path.
        /// </param>
        public void Save(string filePath)
        {
            var serializer = new XmlSerializer(typeof(BlogEntries));
            using (var writer = XmlWriter.Create(filePath))
            {
                serializer.Serialize(writer, this);
            }
        }

        /// <summary>
        /// Persists the <see cref="BlogEntries"/> object.
        /// </summary>
        public void Persist()
        {
            Save(HttpContext.Current.Request.MapPath("entries.xml"));
        }
    }
}
